#include "Log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Common.hpp"
#include <pthread.h>
namespace Tcp
{
    class Tcpsocket;
    using task_t = std::function<void()>;
    const int max_thread_num=10;
    class ThreadData{
        public:
            ThreadData(int sockfd,NetAddr clientaddr,Tcpsocket* tcpsocket):sockfd(sockfd),tcpsocket(tcpsocket),clientaddr(clientaddr){}
        public:
            int sockfd;
            NetAddr clientaddr;
            Tcpsocket* tcpsocket;
    };
    class Tcpsocket : NoCopy
    {
    public:
        Tcpsocket(uint16_t port) : _isrunning(false), _listenfd(-1), _port(port) {}
        ~Tcpsocket() {}
        void Service(int sockfd, NetAddr clientaddr)
    {
        char buf[1024];
        while (true)
        {
            memset(buf, 0, sizeof(buf));
            int n = read(sockfd, buf, sizeof(buf));
            if (n <= 0){
                LOG(LogLevel::INFO) << "client " << clientaddr.stringaddr() << " disconnected";
                break;
            }
            buf[n] = 0;
            LOG(LogLevel::INFO) << "#"<<buf;
            write(sockfd, buf, n);
        }
    }
        void Start()
        {
            _listenfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_listenfd < 0)
            {
                LOG(LogLevel::ERROR) << "create socket failed";
                return;
            }
            LOG(LogLevel::INFO) << "create socket success";
            // bind socket
            _listenaddr.setAddr(_port);
            int ret = bind(_listenfd, (struct sockaddr *)&_listenaddr.getAddr(), sizeof(_listenaddr.getAddr()));
            if (ret < 0)
            {
                LOG(LogLevel::ERROR) << "bind socket failed";
                return;
            }
            LOG(LogLevel::INFO) << "bind socket success";
            // listen socket
            int rets = listen(_listenfd, 10);
            if (rets < 0)
            {
                LOG(LogLevel::ERROR) << "listen socket failed";
                return;
            }
            LOG(LogLevel::INFO) << "listen socket success";
        }
        static void*Rountine(void* arg){
            pthread_detach(pthread_self());
            ThreadData* data=(ThreadData*)arg;
            data->tcpsocket->Service(data->sockfd,data->clientaddr);
            delete data;
            return nullptr;
        }
        void Run()
        {
            _isrunning = true;
            while (_isrunning)
            {
                sleep(1);
                // 获取连接
                struct sockaddr_in peer;
                socklen_t clientlen = sizeof(peer);
                int connfd = accept(_listenfd, (struct sockaddr *)&peer, &clientlen);
                if (connfd < 0)
                {
                    LOG(LogLevel::ERROR) << "accept socket failed";
                    continue;
                }
                NetAddr clientaddr(peer);
                LOG(LogLevel::INFO) << "accept socket success" << clientaddr.stringaddr();
                // 处理链接
            //     pid_t id = fork();
            //     if (id < 0)
            //     {
            //         LOG(LogLevel::FATAL) << "fork eeror";
            //         exit(1);
            //     }
            //     else if (id == 0)
            //     {
            //         // 子进程
            //         // 我们不想让子进程访问listen套接字
            //         close(_listenfd);
            //         if (fork() > 0)
            //         { // 再次fork,子进程退出
            //             exit(0);
            //         }
            //         Service(connfd, clientaddr); // 孤儿进程,系统回收
            //         exit(0);
            //     }
            //     else
            //     {
            //         // 父进程
            //         close(connfd);
            //         int rid = waitpid(id, nullptr, 0);
            //         // 父进程
            //         (void)rid;
            //     }
            ThreadData *data=new ThreadData(_listenfd,_listenaddr,this);
            pthread_t tid;
            pthread_create(&tid, nullptr,Rountine,data);
            //线程池版适合短服务
        //    ThreadPool<task_t> pool(max_thread_num);
        //     pool.Enqueue([this,&connfd,&clientaddr](){
        //         Service(connfd, clientaddr);
        //     });
        }
            _isrunning = false;
    }
        void Stop()
        {
            this->_isrunning = false;
        }

    public:
        bool _isrunning;
        int _listenfd;
        NetAddr _listenaddr;
        uint16_t _port;
    };
}